package cn.xzc.job.pojo;

import java.util.Objects;
import java.util.concurrent.ScheduledFuture;

/**
 * 存储执行任务runnable和定时执行器
 *
 * @author xzc
 * 当前时间 2024-02-12 21:30:00
 */
public final class ScheduledJob {

    private final Job job;

    private volatile ScheduledFuture<?> future;


    public ScheduledJob(Job job) {
        this.job = job;
    }


    /**
     * Return the underlying job
     * 获取具体的job的类型【如：CronJob、FixedDelayJob、FixedRateJob】
     */
    public Job getJob() {
        return this.job;
    }

    /**
     * Trigger cancellation of this scheduled job.
     * This variant will force interruption of the job if still running.
     * <p>
     * 正在当前正在执行的任务，且未来要执行的任务也会中止
     */
    public void cancel() {
        cancel(true);
    }

    /**
     * Trigger cancellation of this scheduled job. 当前执行任务中断
     *
     * @param mayInterruptIfRunning whether to force interruption of the job 是否中断正在执行的任务
     *                              不论mayInterruptIfRunning是true还是false，都会中止未来要执行的任务；但当为true时，会中断正在执行的任务
     */
    public void cancel(boolean mayInterruptIfRunning) {
        ScheduledFuture<?> future = this.future;
        if (future != null) {
            future.cancel(mayInterruptIfRunning);
        }
    }

    public synchronized void setFuture(ScheduledFuture<?> future) {
        this.future = future;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof ScheduledJob)) {
            return false;
        }
        ScheduledJob that = (ScheduledJob) o;
        return Objects.equals(job, that.job) && Objects.equals(future, that.future);
    }

    @Override
    public int hashCode() {
        return Objects.hash(job, future);
    }

    @Override
    public String toString() {
        return this.job.toString();
    }

}